//
//  THFlowEarnMyPubDetailVC.m
//  YJB
//
//  Created by 中电大维 on 2017/1/18.
//  Copyright © 2017年 YJB. All rights reserved.
//

#import "THFlowEarnMyPubDetailVC.h"
#import "HTextViewCell.h"
#import "THFEMyPublishDetailModel.h"
#import "THIconTableViewCell.h"
#import "THFlowEarnPublishTaskVC.h"
#import "THFlowEarnManaulPublishVC.h"

@interface THFlowEarnMyPubDetailVC ()<UITextFieldDelegate>
@property (nonatomic, strong)NSMutableArray *arrayDataSouce;
@property (nonatomic, strong)UIButton *detailButton;
@end

@implementation THFlowEarnMyPubDetailVC
{
//    BOOL _isEditing;
    NSArray *_titles;
    NSArray *_alerts;
    THFEMyPublishDetailModel *_model;
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidBeginEditingNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_model) {
         [self loadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNav];
//    _isEditing = NO;
    _model = [[THFEMyPublishDetailModel alloc] init];
    
    if (self.isAuto) {
        _titles = [NSArray arrayWithObjects:@"任务标题",@"任务地址",@"广告数量",@"广告单价",@"完        成",@"状        态", nil];
        _alerts = [[NSArray alloc] initWithObjects:@"请输入任务标题",@"请输入任务地址",@"请输入名额数量不少于1000",@"请输入任务单价",@"请输入任务总价",nil];
    }else{
        _titles = [NSArray arrayWithObjects:@"任务标题",@"任务地址",@"停留时间",@"广告数量",@"广告单价",@"完        成",@"状        态", nil];
        _alerts = [[NSArray alloc] initWithObjects:@"请输入任务标题",@"请输入任务地址",@"请选择停留时间",@"请输入名额数量不少于1000",@"请输入任务单价",@"请输入任务总价",nil];
    }
    
    
    self.title = @"发布详情";
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.tableView setSeparatorColor:[UIColor colorWithHexString:@"e5e5e5"]];
    //[self.tableView setSeparatorColor:[UIColor colorWithHexString:@"eeeeee"]];
    self.tableView.backgroundColor = kUIColorFromRGB(0xeeeeee);
    [self.tableView registerClass:[HTextViewCell class] forCellReuseIdentifier:HTextViewCellID];
    [self.tableView registerClass:[THIconTableViewCell class] forCellReuseIdentifier:THIconCellID];
    [self loadData];
    [self.view addSubview:self.detailButton];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(beginEditing) name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)beginEditing
{

}
- (void)didChange:(NSNotification *)noti
{
    /// 数据源赋值
    UITextField *textField=noti.object;
    NSIndexPath *indexPath = textField.indexPath;
    [self.arrayDataSouce replaceObjectAtIndex:indexPath.row withObject:textField.text];
    
}

- (void)loadData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    NSString *url = [[NSString alloc] init];
    if (self.isAuto) {
        params[@"action"] = @"get_surf_one";
        url = THURL(@"traffic.php");
    }else{
        params[@"action"] = @"get_mypublish_one";
        url = THURL(@"manual.php");
    }
    params[@"makegold"] = @{@"task_id":self.taskId,
                            @"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    
    
    [YJNetworkTool postWithUrl:url parameters:params success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        NSString *code = responseObject[@"return"][@"code"];
        
        if (code.integerValue == 200)
        {
            if (self.isAuto) {
                NSDictionary *dict = responseObject[@"return"][@"data"];
                [_model setValuesForKeysWithDictionary:dict];
                _model.ID = [dict objectForKey:@"id"];
                [self setDict:dict];
            }else{
                NSArray *array = responseObject[@"return"][@"data"];
                NSDictionary *dict = [array firstObject];
                [_model setValuesForKeysWithDictionary:dict];
                _model.ID = [dict objectForKey:@"id"];
                [self setDict:dict];
            }
            
            if ([self.surfedcount integerValue]) {
                self.navigationItem.rightBarButtonItem = nil;
                self.detailButton.hidden = YES;
            }
        }else{
            [MBProgressHUD showError:responseObject[@"return"][@"message"]];
        }
    } failure:^(NSError *error) {
        
        [self loadData];
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
    }];
}

- (void)setDict:(NSDictionary *)dict
{
    if ([dict objectForKey:@"sitename"]) {
        self.arrayDataSouce[0] = [NSString stringWithFormat:@"%@",[dict objectForKey:@"sitename"]];
    }
    if ([dict objectForKey:@"url"]) {
        self.arrayDataSouce[1] = [NSString stringWithFormat:@"%@",[dict objectForKey:@"url"]];
    }
    if ([dict objectForKey:@"total_num"]) {
        self.arrayDataSouce[_titles.count-4] = [NSString stringWithFormat:@"%@个",[dict objectForKey:@"total_num"]];
    }
    if ([dict objectForKey:@"gold_one"]) {
        self.arrayDataSouce[_titles.count-3] = [NSString stringWithFormat:@"%@金币",[dict objectForKey:@"gold_one"]];
    }
    self.arrayDataSouce[_titles.count-2] = [NSString stringWithFormat:@"%@个",self.surfedcount];
    
    if ([dict objectForKey:@"froze"]) {
        self.arrayDataSouce[_titles.count-1] = [[dict objectForKey:@"froze"] intValue]?@"异常":@"正常";
    }
    if (self.isAuto) {
        self.arrayDataSouce[_titles.count-2] = [NSString stringWithFormat:@"%@个",self.surfedcount];;
    }else{
        if ([dict objectForKey:@"stop_sec"]) {
            self.arrayDataSouce[2] = [NSString stringWithFormat:@"%@秒",[dict objectForKey:@"stop_sec"]];
        }
    }
    [self reloadData];
}

- (void)choiceStoptimeClick:(UIButton *)button
{
    [self.tableView endEditing:YES];
}

- (void)detailClick:(UIButton *)button
{
    //册除此任务
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    params[@"action"] = @"del_surf_one";
    params[@"makegold"] = @{@"task_id":self.taskId,
                            @"username":userName,
                            @"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    NSString *url = THURL(@"manual.php");
    
    if (self.isAuto) {
        params[@"action"] = @"del_traff_one";
        url = THURL(@"traffic.php");
    }else{
        params[@"action"] = @"del_surf_one";
        url = THURL(@"manual.php");
    }
    
    [YJNetworkTool postWithUrl:url parameters:params success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        NSString *code = responseObject[@"return"][@"code"];
        
        if (code.integerValue == 200)
        {
            [MBProgressHUD showMessage:@"删除任务成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [MBProgressHUD showError:responseObject[@"return"][@"message"]];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
    }];
    
}
- (void)editClick
{
    if (self.isAuto) {
        THFlowEarnManaulPublishVC *vc = [[THFlowEarnManaulPublishVC alloc] init];
        vc.isEditDetail = YES;
        vc.model = _model;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        THFlowEarnPublishTaskVC *vc = [[THFlowEarnPublishTaskVC alloc] init];
        vc.isEditDetail = YES;
        vc.model = _model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)reloadData{
    [self.tableView reloadData];
//    if (_isEditing) {
//        [self.detailButton mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(92+50*(_titles.count-1)+30);
//        }];
//    }else{
//        [self.detailButton mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(92+50*_titles.count+30);
//        }];
//    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 100) {
        return 1;
    }
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (tableView.tag) {
//        return self.times.count;
//    }
    if (!section || section == 2) {
        return 1;
    }
//    if (_isEditing) {
//        return _titles.count-1;
//    }
    return _titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        THIconTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:THIconCellID forIndexPath:indexPath];
        cell.model = _model;
//        NSString *urlString = _model.surf_icon;
//        if (![urlString hasPrefix:@"http"] && urlString)
//            urlString = [@"http://" stringByAppendingString:urlString];
//        [cell.iconImage sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:Image(@"th_cpc_default_normal")];
//        cell.username.text = [NSString stringWithFormat:@"%@",_model.username];
//        cell.state.text = [NSString stringWithFormat:@"共 %@ 金币",_model.totalgold];
//        cell.time.text = [_model.create_time stringWithDateFormat:@"yyyy.MM.dd hh:mm"];
        return cell;
    }else if (indexPath.section == 2) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailID"];
        if (!cell) {
            cell = [[UITableViewCell alloc] init];
            cell.backgroundColor = [UIColor clearColor];
            [cell addSubview:self.detailButton];
            [self.detailButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(0);
                make.left.mas_equalTo(15);
                make.right.mas_equalTo(-15);
                make.height.mas_equalTo(43);
            }];
        }
        return cell;
    }
    
    HTextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HTextViewCellID];
    if (!cell) {
        cell = [[HTextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HTextViewCellID];
        cell.textField.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    //设置完成的文字颜色
    if ((indexPath.row == 5 && !self.isAuto)||(indexPath.row == 4 &&self.isAuto)) {
        cell.textField.textColor = kUIColorFromRGB(0xff783c);
    }
    [cell setTitleString:_titles[indexPath.row] andDataString:self.arrayDataSouce[indexPath.row] andIndexPath:indexPath];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        return 47;
    }
    return 80;//显示任务图标和时间的组的高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 20;
    }
    return 6;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = kUIColorFromRGB(0xeeeeee);
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = kUIColorFromRGB(0xeeeeee);
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)setNav{
    //返回按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editClick)];
}
- (UIButton *)createButton
{
    UIButton *button = [[UIButton alloc] init];
    button.backgroundColor = kUIColorFromRGB(0xff783c);
    [button setTitleColor:WHITECOLOR forState:UIControlStateNormal];
    [button setTitle:@"删除此任务" forState:UIControlStateNormal];
    [button setTitle:@"提交修改" forState:UIControlStateSelected];
    [button addTarget:self action:@selector(detailClick:) forControlEvents:UIControlEventTouchUpInside];
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:3.0];
    return button;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    [self.tableView endEditing:YES];
}
- (NSMutableArray *)arrayDataSouce{
    if (!_arrayDataSouce) {
        _arrayDataSouce = [NSMutableArray array];
        [_arrayDataSouce addObject:@""];
        [_arrayDataSouce addObject:@""];
        [_arrayDataSouce addObject:@""];
        [_arrayDataSouce addObject:@""];
        [_arrayDataSouce addObject:@""];
        [_arrayDataSouce addObject:@""];
        [_arrayDataSouce addObject:@""];
    }
    return _arrayDataSouce;
}

- (UIButton *)detailButton
{
    if (!_detailButton) {
        _detailButton = [self createButton];
        //[self.view addSubview:_detailButton];
    }
    return _detailButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
